﻿using DevExpress.XtraEditors;
using JZ_UDI.CommonHelper;
using JZ_UDI.DataAccess;
using JZ_UDI.DataAccess.DataEntity;
using NLog;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LogLevel = NLog.LogLevel;

namespace JZ_UDI.Settings
{
    public partial class frmUdiAdd : UIForm   //DevExpress.XtraEditors.XtraForm
    {
        public frmUdiAdd()
        {
            InitializeComponent();
        }

        // 定义委托，在窗体关闭时将Product对象返回给主窗体
        public delegate void FormBClosedEventHandler(object sender, Product result);

        // 定义事件  
        public event FormBClosedEventHandler FormBClosed;

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtProductName.Text) || txtProductName.Text.Equals("产品名称不能为空！"))
            {
                txtProductName.Text = "产品名称不能为空！";
                txtProductName.ForeColor = Color.Red;
                return;
            }
            //验证包装数量代码
            if (string.IsNullOrEmpty(cmbPackagingQuantityCode.Text) || cmbPackagingQuantityCode.Text.Equals("包装数量代码不能为空！"))
            {
                cmbPackagingQuantityCode.Text = "包装数量代码不能为空！";
                cmbPackagingQuantityCode.ForeColor = Color.Red;
                return;
            }


            //计算UDI有，无校验码
            txtUdiNoCheckCode.Text = cmbPackagingQuantityCode.Text.Trim().ToString() + txtVendorCode.Text.Trim().ToString() + txtSerialNumber.Text.Trim();
            try
            {
                var count = GetUdiCheckCodeHelper.GetUdiCheckCode(txtSerialNumber.Text.Trim(), txtVendorCode.Text.Trim());
                txtUdiHaveCheckCode.Text = cmbPackagingQuantityCode.Text.Trim().ToString() + txtVendorCode.Text.Trim().ToString() + txtSerialNumber.Text.Trim().ToString() + count.ToString();
            }
            catch (Exception ex)
            {
                Global.SaveLogger(NLog.LogLevel.Error, Global.logger.Name, ex.Message);
                throw new Exception(ex.Message);
            }


            Product product = new Product();
            #region 生成新的Product

            if (!string.IsNullOrEmpty(txtSerialNumber.Text))
            {
                product.SerialNumber = txtSerialNumber.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtProductName.Text))
            {
                product.ProductName = txtProductName.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtComponentName.Text))
            {
                product.ComponentName = txtComponentName.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtProductModel.Text))
            {
                product.ProductModel = txtProductModel.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtProductSpecification.Text))
            {
                product.ProductSpecification = txtProductSpecification.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtMaterialCode.Text))
            {
                product.MaterialCode = txtMaterialCode.Text.Trim();
            }
            if (!string.IsNullOrEmpty(cmbSterilizationMethod.Text))
            {
                product.SterilizationMethod = cmbSterilizationMethod.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtProductCode.Text))
            {
                product.ProductCode = txtProductCode.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtRegistrationNumber.Text))
            {
                product.RegistrationNumber = txtRegistrationNumber.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtProductionLicenseNumber.Text))
            {
                product.ProductionLicenseNumber = txtProductionLicenseNumber.Text.Trim();
            }
            if (!string.IsNullOrEmpty(cmbPackagingQuantityCode.Text))
            {
                product.PackagingQuantityCode = cmbPackagingQuantityCode.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtVendorCode.Text))
            {
                product.VendorCode = txtVendorCode.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtUdiNoCheckCode.Text))
            {
                product.UdiNoCheckCode = txtUdiNoCheckCode.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtUdiHaveCheckCode.Text))
            {
                product.UdiHaveCheckCode = txtUdiHaveCheckCode.Text.Trim();
            }
            if (!string.IsNullOrEmpty(cmbProductCategory.Text))
            {
                product.ProductCategory = cmbProductCategory.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtDrainageTubeDiameter.Text))
            {
                product.DrainageTubeDiameter = txtDrainageTubeDiameter.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtDrainageTubeLength.Text))
            {
                product.DrainageTubeLength = txtDrainageTubeLength.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtDrainageBallVolume.Text))
            {
                product.DrainageBallVolume = txtDrainageBallVolume.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtDrainageBagVolume.Text))
            {
                product.DrainageBagVolume = txtDrainageBagVolume.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtProductSpecificationNumber.Text))
            {
                product.ProductSpecificationNumber = txtProductSpecificationNumber.Text.Trim();
            }
            if (!string.IsNullOrEmpty(cmbSurfaceStates.Text))
            { 
                product.SurfaceStates = cmbSurfaceStates.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtDescription.Text))
            {
                product.SurfaceStates = txtDescription.Text.Trim();
            }
            #endregion

            using (var context = new EFDbContext())
            {
                context.Products.Add(product);
                try
                {
                    int count = context.SaveChanges();
                    if (count <= 0)
                    {
                        throw new DbUpdateException("UDI添加失败!");
                    }
                    else
                    {
                        // 触发事件，传递结果给订阅者  
                        FormBClosed?.Invoke(this, product);
                    }
                }
                catch ( DbUpdateException ex)
                {
                    Global.SaveLogger(LogLevel.Error, Global.logger.Name, "新增UDI序号："+ex.Message + txtSerialNumber.Text.Trim());
                }
              
            }
            Global.SaveLogger(LogLevel.Info, Global.logger.Name, "新增UDI序号："+txtSerialNumber.Text.Trim()+"厂商代码："+product.VendorCode.ToString());
            this.DialogResult = DialogResult.OK;
        }

        private void txtProductName_MouseDown(object sender, MouseEventArgs e)
        {
            if (txtProductName.Text.Trim().Equals("产品名称不能为空！"))
            {
                txtProductName.Text = "";
                txtProductName.ForeColor = Color.Black;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Global.SaveLogger(LogLevel.Info, Global.logger.Name, "取消新增UDI");
            this.DialogResult = DialogResult.Cancel;
        }

        private void frmUdiAdd_Load(object sender, EventArgs e)
        {
            //厂商编号
            txtVendorCode.Text = Global.VendorCode;

            //序号自增 序号最大到999
            using (var context = new EFDbContext())
            {
                //查询当前厂商代码
                var lists=context.Products.ToList().FindAll(o => o.VendorCode == Global.VendorCode);
                int maxSeri;
                if (lists.Count <= 0)
                {
                    maxSeri = 0;
                }
                else
                {
                    maxSeri = int.Parse(lists.Max(o => o.SerialNumber)) + 1;
                }
                if (maxSeri > 999)
                {
                    MessageBox.Show("UDI序号资源不足,请联系管理员更换厂商代码！");
                    Global.SaveLogger(LogLevel.Warn, Global.logger.Name, "UDI序号资源不足，已超出最大编号999,请联系管理员更换厂商代码");
                    this.Close();
                }
                txtSerialNumber.Text = maxSeri.ToString().PadLeft(3,'0');
            }
        }




    }
}